package com.zhongxi.guoyuan.view.personalCenter;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.weigan.loopview.LoopView;
import com.weigan.loopview.OnItemSelectedListener;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.coinPost.LogisiticsInfoAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.coinPost.LogisiticsData;
import com.zhongxi.guoyuan.entity.coinPost.LogisiticsResult;
import com.zhongxi.guoyuan.entity.seller.ExpressCompany;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.view.rewardCoin.RewardCoinShoperAtivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


public class LogisticsSearchActivity extends BaseActivity implements View.OnClickListener {

    private String expressNum;
    private ImageView iv_logisitics_search;
    private EditText et_expressNumber;
    private List<String> spList;
    private List<ExpressCompany> expressCompanies;
    private String trim;
    private ListView listView;
    private LogisiticsInfoAdapter infoAdapter;
    private TextView tv_express;
    private int position = 0;
    private LinearLayout linear_spinner;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_logistics_search);
        initTitle();
        tvTitle.setText("快递查询");
        tv_express = (TextView) findViewById(R.id.tv_express);
        linear_spinner = (LinearLayout) findViewById(R.id.linear_spinner);
        iv_logisitics_search = (ImageView) findViewById(R.id.iv_logisitics_search);
        et_expressNumber = (EditText) findViewById(R.id.et_expressNumber);
        listView = (ListView) findViewById(R.id.listView);
    }

    @Override
    protected void initData() {
        super.initData();

        infoAdapter = new LogisiticsInfoAdapter(this);
        listView.setAdapter(infoAdapter);

        TextView tv = new TextView(context);
        tv.setGravity(Gravity.CENTER);
        tv.setText("亲,暂时还没有物流数据哦!");
        tv.setTextSize(20);
        listView.setEmptyView(tv);

        spList = new ArrayList<String>();
        expressCompanies = new ArrayList<>();
        JSONObject express = null;
        try {
            express = new JSONObject(MyApplication.getInstance().getLogistics());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Iterator<String> iterator = express.keys();
        while (iterator.hasNext()) {
            ExpressCompany expressCompany = new ExpressCompany();
            String key = iterator.next();
            String value = express.optString(key);
            expressCompany.setExpressNum(key);
            expressCompany.setExpressName(value);
            spList.add(value);
            expressCompanies.add(expressCompany);
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();

        ivBack.setOnClickListener(this);
        linear_spinner.setOnClickListener(this);
        iv_logisitics_search.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.iv_logisitics_search:

                trim = et_expressNumber.getText().toString().trim();
                if (trim != null && !"".equals(trim)) {
                    searchInfo(trim);
                }
                break;
            case R.id.linear_spinner:
                showSelectExpressage();
                break;
        }
    }

    private void showSelectExpressage() {
        final AlertDialog ad = new AlertDialog.Builder(context).create();
        View expressView = this.getLayoutInflater().inflate(R.layout.dialog_view, null);
        ad.setView(expressView);
        ad.setCanceledOnTouchOutside(false);
        ad.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    ad.dismiss();
                    return true;
                }
                return false;
            }
        });
        TextView tvNo = (TextView) expressView.findViewById(R.id.tv_no);
        TextView tvYes = (TextView) expressView.findViewById(R.id.tv_yes);
        LoopView loopView = (LoopView) expressView.findViewById(R.id.loopView);
        loopView.setItems(spList);
        loopView.setInitPosition(0);
        loopView.setNotLoop();
        loopView.setListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                position = index;
            }
        });

        tvNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ad.dismiss();
            }
        });
        tvYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ad.dismiss();
                String s = spList.get(position);
                tv_express.setText(s);
                for (ExpressCompany ec : expressCompanies) {
                    if (s.equals(ec.getExpressName())) {
                        expressNum = ec.getExpressNum();
                    }
                }
            }
        });
        ad.show();

    }

    /**
     * 查询信息
     *
     * @param trim
     */
    private void searchInfo(String trim) {

        Map<String, String> map = new HashMap<>();

        map.put("shipperCode", expressNum);
        map.put("logisticCode", trim);

        getServer(Url.LOGISITICS_SEARCH, map, "", false, null, "post");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);

        Gson gson = new Gson();

        LogisiticsResult result = gson.fromJson(response, LogisiticsResult.class);
        MyApplication.getInstance().setSpValue(result.getSafeobj());

        if (null != result.getData() && !"".equals(result.getData())) {
            showLogisitics(result.getData());
        }

    }

    private void showLogisitics(LogisiticsData logisitics) {


        List<LogisiticsData.Traces> traces = logisitics.getTraces();
        if (null != traces && !"".equals(traces)) {
            Collections.reverse(traces);
            infoAdapter.setList(traces);
        } else {
            showShortToast("暂无物流信息");
        }
    }


    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse baseResponse = gson.fromJson(response, BaseResponse.class);
        if (baseResponse.getSafeobj() != null && !"".equals(baseResponse.getSafeobj())) {
            MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
        }
    }
}
